package com.shopng.controller;

import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.authentication.WebAuthenticationDetails;
import org.springframework.security.web.context.HttpSessionSecurityContextRepository;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.shopng.model.User;
import com.shopng.service.UserService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

@Api(tags = { "User" })
@Controller
@RequestMapping("/user")
public class UserController
{
  private Logger logger = LoggerFactory.getLogger(UserController.class);
  
  @Autowired
  private UserService userService;
  
  @Autowired
  protected AuthenticationManager authenticationManagerBean;
  
  @Autowired
  protected BCryptPasswordEncoder passwordEncoder;
  /*
   * http://localhost:8080/getUserInfo
   */
  
  @ApiOperation(value = "login")
  @RequestMapping(value = "/login", method = RequestMethod.GET)
  public String login()
  {
    return "user/login";
  }
  
  @ApiOperation(value = "register")
  @RequestMapping(value = "/register", method = RequestMethod.GET)
  public String register()
  {
    logger.info("get register:{}", new Date());
    return "user/register";
  }
  
  @ApiOperation(value = "do register")
  @RequestMapping(value = "/register", method = RequestMethod.POST, consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
  @ResponseBody
  public User doRegister(User user, HttpServletRequest request)
  {
    logger.info("get register:{}", user);
    user.setName("NG"+System.currentTimeMillis());
    
    User reg = new User();
    BeanUtils.copyProperties(user, reg);
    reg.setPassword(passwordEncoder.encode(user.getPassword()));
    Integer userId = userService.create(reg);
    user.setId(userId);
    UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(user.getName(),user.getPassword());
    try
    {
      token.setDetails(new WebAuthenticationDetails(request));
      Authentication authenticatedUser = authenticationManagerBean.authenticate(token);
      SecurityContextHolder.getContext().setAuthentication(authenticatedUser);
      request.getSession().setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY,
          SecurityContextHolder.getContext());
    }
    catch (AuthenticationException e)
    {
      logger.error("Authentication failed:{}",e);
    }
    return user;
  }
  
  @ApiOperation(value = "getUserInfo", notes = "requires noting")
  @RequestMapping(value = "/getUserInfo", method = RequestMethod.GET)
  @ResponseBody
  public List<User> getUserInfo()
  {
    List<User> users = userService.findAll();
    if (users != null)
    {
      logger.info("user.getAge():{}", users.toString());
    }
    return users;
  }
}
